import { Provide, httpError, Inject, Context } from "@midwayjs/core";
import { UserEntity } from "../entity/user.entity";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Repository } from "typeorm";
import { JwtService } from "@midwayjs/jwt";
import { UserMapper } from "../mapper/user.mapper";
import { Resultes } from "../interface";
import { TokenService } from "./token.service";

@Provide()
export class UserService {
  @InjectEntityModel(UserEntity)
  userModal: Repository<UserEntity>;

  @Inject()
  jwtService: JwtService;

  @Inject()
  tokenService: TokenService;

  @Inject()
  ctx: Context;

  @Inject()
  userMapper: UserMapper;

  async register(userEntity: UserEntity) {
    const { username } = userEntity;
    const findRes = await this.userMapper.getUserByUserName(username);
    if (findRes) throw new httpError.BadRequestError("用户已存在");

    const newUser = await this.userModal.save(userEntity);
    return {
      id: newUser.id,
      username: newUser.username,
    };
  }

  async login(options: { username: string; password: string }) {
    const { username } = options;
    const findRes = await this.userModal.findOne({
      where: {
        username,
      },
    });
    if (!findRes) throw new httpError.BadRequestError("不存在该用户");
    const token = await this.tokenService.getToken(username);
    return {
      token,
      username,
    };
  }

  async getUser(id: number) {
    const findRes = await this.userModal.findOne({
      where: {
        id,
      },
    });
    if (!findRes) throw new httpError.BadRequestError("不存在该用户");

    return findRes;
  }

  async getList(pageSize: number, pageNum: number, username: string) {
    const queryBuilder = this.userModal.createQueryBuilder("user");
    // 分页查询
    const [users, total] = await queryBuilder
      .skip((pageNum - 1) * pageSize) // 跳过的记录数
      .take(pageSize) // 每页记录数
      .where("c_user.username LIKE :username", { username: `%${username}%` })
      .getManyAndCount(); // 获取记录总数

    return Resultes.pageList({
      list: users,
      total,
      pageNum,
      pageSize,
    });
  }
}
